package imdb;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.google.gson.JsonObject;

import play.libs.WS;
import play.libs.WS.HttpResponse;
import play.libs.WS.WSRequest;

public class ImdbApi {
	
	public static Logger LOGGER = Logger.getLogger(ImdbApi.class);
	
	public final static String IMDB_API_URL = "http://mymovieapi.com/";
	public final static String IMDB_TITLE_PARAM = "q";
	public final static String IMDB_TYPE_PARAM = "type";
	
	public final static String IMDB_TYPE_VALUE = "json";
	
	public final static int	   RESPONSE_CODE_SUCCESS = 1;
	public final static int	   RESPONSE_CODE_NOT_FOUND = 2;
	
	public static String cleanFileName(String fileName) {
		try {
			LOGGER.info("Cleaning : " + fileName);
			fileName = fileName.replaceAll("(?i)[-_.]|(flv)|(avi)|(mkv)|(mp4)|(divx)|(xvid)", " ").trim();
			LOGGER.info("OK =>" + fileName);
			return fileName;
		} catch (Exception e) {
			LOGGER.error("Erreur de nettoyage de nom de fichier " + fileName, e);
			return null;
		}
	}
	
	public static WSRequest createRequestWithTitle(String title) {
		WSRequest result = WS.url(IMDB_API_URL);
		Map<String, String> params = new HashMap<String, String>();
		
		params.put(IMDB_TITLE_PARAM, title);
		params.put(IMDB_TYPE_PARAM, IMDB_TYPE_VALUE);
		
		result.setParameters(params);
		return result;
	}
	
	public static Integer handleResponse(HttpResponse response) {
		if (response.getJson().isJsonObject() && response.getJson().getAsJsonObject() != null && response.getJson().getAsJsonObject().get("code").getAsInt() == 404) {
			return RESPONSE_CODE_NOT_FOUND;
		} else {
			LOGGER.info("REPONSE ImDb : " + response.getJson());
			LOGGER.info("TITRE ImDb " + response.getJson().getAsJsonArray().get(0).getAsJsonObject().get("title"));
		}
		return RESPONSE_CODE_SUCCESS;
	}
	
	public static JsonObject searchByFileName(String fileName) {
		try {
			fileName = cleanFileName(fileName);
			String[] fileNameWords = fileName.split(" ");
			Integer wordsCount = fileNameWords.length;
			LOGGER.info("Nombre de mots dans le nom de fichier : " + wordsCount);
			
			for (Integer currentCount = wordsCount; currentCount > 0; currentCount--) {
				String title = "";
				for (Integer wordNum = 0; wordNum != currentCount; wordNum++) {
					title += fileNameWords[wordNum] + " ";
				}
				title = title.trim();
				LOGGER.info("Recherche avec " + currentCount + " mots...");
				LOGGER.info("Titre : " + title);
				WSRequest request = createRequestWithTitle(title);
				HttpResponse response = request.get();
				if (handleResponse(response).equals(RESPONSE_CODE_SUCCESS)) {
					return response.getJson().getAsJsonArray().get(0).getAsJsonObject();
				}
			}
			return null;
		} catch (Exception e) {
			LOGGER.error("Erreur lors de la communication vers IMDB : ", e);
			return null;
		}
	}
	
}
